package wget

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"time"
	//"golang.org/x/sync/semaphore"
)

func DownUrlFile(url string, fname string) int {
	params := []string{
		"-t",
		"1",
		"--timeout=3",
		"-O",
		fname,
		url,
		//fmt.Sprintf("rtmp://127.0.0.1:1935/live/stream%d", value.ID),
	}
	cmd := exec.Command("wget", params...)
	err := cmd.Start()
	if err != nil {
		return -1
	}
	ret, err := cmd.Process.Wait()
	if err != nil {
		return -2
	}
	exitCode := ret.ExitCode()
	if exitCode != 0 {
		//删除文件
		os.Remove(fname)
	}
	return exitCode
}

func DownUrlFileToPath(url string, fname string, path string) int {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		//创建目录
		os.MkdirAll(path, os.ModePerm)
	}
	name := fmt.Sprintf("%s/%s", path, fname)
	params := []string{
		"-t",
		"1",
		"--timeout=5",
		"-O", //指定目录
		name,
		url,
	}

	cmd := exec.Command("wget", params...)
	err := cmd.Start()
	if err != nil {
		return -1
	}
	ret, err := cmd.Process.Wait()
	if err != nil {
		return -2
	}
	//exitCode := ret.ExitCode()
	//if exitCode != 0 {
	//	//删除文件
	//	os.Remove(name)
	//}
	//return exitCode
	return ret.ExitCode()
}

// 上传文件
// url                请求地址
// params        post form里数据
// nameField  请求地址上传文件对应field
// fileName     上传文件名
// file         原始文件文件
func UploadFile(urlAddr string, params map[string]string, nameField, fileName string, srcName string) (string, error) {
	body := new(bytes.Buffer)

	writer := multipart.NewWriter(body)

	formFile, err := writer.CreateFormFile(nameField, fileName)
	//_, err := writer.CreateFormFile(nameField, fileName)
	if err != nil {
		return "", err
	}
	srcFile, err := os.Open(srcName)
	if err != nil {
		return "", err
	}
	defer srcFile.Close()

	_, err = io.Copy(formFile, srcFile)
	if err != nil {
		return "", err
	}

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	err = writer.Close()
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", urlAddr, body)
	if err != nil {
		return "", err
	}

	//req.Header.Add("Content-Type", writer.FormDataContentType())
	req.Header.Add("Content-Type", writer.FormDataContentType())
	httpClient := &http.Client{
		Timeout: 3 * time.Second,
	}
	resp, err := httpClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

func UploadFtp(urlAddr string, params url.Values, srcName string, fileName string) {
	//body := new(bytes.Buffer)
	//data := make(url.Values)
	//writer := multipart.NewWriter(body)
	//for key, val := range params {
	//	_ = writer.WriteField(key, val)
	//}

	res, err := http.PostForm(urlAddr, params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer res.Body.Close()

	content, err := ioutil.ReadAll(res.Body)
	if err == nil {
		fmt.Println(string(content))
	}

}

/*
	params := make(map[string]string)
	params["deviceId"] = "192.168.40.153"
	params["spaceNo"] = "1"
	params["plateNo"] = "闽D"
	params["plateColor"] = "绿"
	params["dateTime"] = time.Now().Format("2006-01-02 00:01:02")
	content, err := UploadFile("http://192.168.40.154:6666/pushPlaceHolderInfo", params, "photo", "1.jpg", "/home/xmrbi/aiFindCar/database/img/save/1.jpg")
	fmt.Println(content, ",", err)
*/

// 上传文件
// url                请求地址
// params        post form里数据
// nameField  请求地址上传文件对应field
// fileName     上传文件名
// file         原始文件文件
func UploadFileBase64(urlAddr string, params map[string]string, nameField, fileName string, srcName string) (string, error) {
	body := new(bytes.Buffer)

	writer := multipart.NewWriter(body)

	formFile, err := writer.CreateFormFile(nameField, fileName)
	//_, err := writer.CreateFormFile(nameField, fileName)
	if err != nil {
		return "", err
	}
	srcFile, err := os.Open(srcName)
	if err != nil {
		return "", err
	}
	defer srcFile.Close()

	_, err = io.Copy(formFile, srcFile)
	if err != nil {
		return "", err
	}

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	err = writer.Close()
	if err != nil {
		return "", err
	}

	req, err := http.NewRequest("POST", urlAddr, body)
	if err != nil {
		return "", err
	}

	//req.Header.Add("Content-Type", writer.FormDataContentType())
	req.Header.Add("Content-Type", writer.FormDataContentType())
	httpClient := &http.Client{
		Timeout: 3 * time.Second,
	}
	resp, err := httpClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

//上传表单
func PostUrlForm(urlAddr string, params url.Values) {
	//body := new(bytes.Buffer)
	//data := make(url.Values)
	//writer := multipart.NewWriter(body)
	//for key, val := range params {
	//	_ = writer.WriteField(key, val)
	//}

	res, err := http.PostForm(urlAddr, params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer res.Body.Close()

	content, err := ioutil.ReadAll(res.Body)
	if err == nil {
		fmt.Println(string(content))
	}

}
